<!--
Module: NBIOT 配置页面
Author: 吴金根
date:2017/11/14
-->
<template>
 <div class="page-box">
    <Nav :indexs="1"  @clickit="gettoken"></Nav>
    <div class="addconfig-page-box">
      <div class="addconfig-page" :style="addconfighigh">
          <div class="group-part">
                  <div class="btn-wrap">
                      <!-- 驱动：<el-input v-model="nm1" style="width: 100px;" placeholder="请输入内容"></el-input> -->
                      <!-- <el-button type="primary" icon="search" @click="query('0', 1)"></el-button> -->
                      <div class="title">驱动</div>
                      <el-button-group class="right-btn">
                          <el-button type="primary" icon="plus" @click="addqd"></el-button>
                          <el-button type="primary" icon="edit" :disabled="isedit" id="edit" @click="editrow"></el-button>
                          <el-button type="primary" icon="delete" :disabled="isedit" id="delete"  @click="deleteRow"></el-button>
                      </el-button-group>
                  </div>
                
                  <div class="table-list" id="qdlist">
                      <el-table
                          :data="rowsqd"
                          border
                          stripe
                          @row-click="onchange"
                          highlight-current-row="true"
                          :max-height="SystemTable"
                          >
                          <el-table-column
                              prop="name"
                              label="名称"
                              align="center">
                          </el-table-column>
                          <el-table-column
                              prop="type"
                              label="标识"
                              align="center">
                                <!-- <template scope="scope">
                                    <span style="margin:0 3px;" :key="item" v-for="item in scope.row.protocols ">{{item}}</span>
                              </template> -->
                          </el-table-column>
                          <el-table-column
                              prop="enable"
                              label="是否启用"
                              align="center" :formatter="formattertxt">
                          </el-table-column>
                      </el-table>
                  </div>
          </div>
          <div class="group-part group-part-2">
                  <div class="btn-wrap">
                      <div class="title">协议</div>
                      <el-button-group class="right-btn">
                          <el-button type="primary" icon="plus" :disabled="iseditadd" @click="addxy"></el-button>
                          <el-button type="primary" icon="edit" :disabled="isedit2" id="editxy" @click="editrowxy"></el-button>
                          <el-button type="primary" icon="delete" :disabled="isedit2" id="deletexy"  @click="deleteRowxy"></el-button>
                      </el-button-group>
                  </div>
                  <div class="table-list">
                      <el-table
                          border
                          :data="xyrows"
                          stripe
                        @row-click="onchange2"
                          :max-height="SystemTable"
                          highlight-current-row="true"
                          >
                          <el-table-column
                              prop="name"
                              label="名称"
                              
                              align="left">
                          </el-table-column>
                          <el-table-column
                              prop="name"
                              label="标识"
                              align="left">
                                
                          </el-table-column>
                          <el-table-column
                          label="排序"
                            type="index"
                            width="80"
                            align="center"
                            :index="indexMethod">
                          </el-table-column>
                      </el-table>
                  </div>
          </div>
          <!--添加驱动列表弹窗-->
          <el-dialog :title="tnm" @close="closeqddialog" :visible.sync="dialog1">

              <el-form class="qd-wrap" size="tiny" :inline="true" ref="qdform" :rules="rules" :model="qdform" label-width="80px" label-position="left"  v-loading.fullscreen.lock="loading" element-loading-text="信息保存中">
                 <div class="qdform-inline">
                      <el-form-item label="名称" prop="name">
                          <el-input v-model="qdform.name" placeholder=""></el-input>
                      </el-form-item>
                      <el-form-item label="分组" prop="prefix">
                          <el-input v-model="qdform.prefix" placeholder=""></el-input>
                      </el-form-item>
                  </div>
                   <div class="qdform-inline">
                      <el-form-item label="控制参数" prop="host">
                          <el-input v-model="qdform.host" placeholder=""></el-input>
                      </el-form-item>
                      
                      <el-form-item label="端口" prop="port">
                          <el-input v-model.number="qdform.port"></el-input>
                      </el-form-item>
                  </div>
              
                  <el-form-item label="驱动选择"  prop="type" class="xyselect-input">
                   
                      <el-select v-model="qdform.type">
                          <el-option v-for="item in drives" :key="item.value" :label="item.label" :value="item.value"></el-option>
                      </el-select>
                  </el-form-item>
             
                  <div class="qdform-wrap">
                      <el-checkbox v-model="qdform.enable">启用</el-checkbox>
                  </div>
                
                  <el-form-item class="submit-btn">
                      <el-button type="primary" @click="submitqdForm('qdform')">保存</el-button>
                      <el-button @click="resetqdForm()">取消</el-button>
                  </el-form-item>

              </el-form>
          </el-dialog>
          <!--添加驱动列表弹窗-->
            <!--添加协议列表弹窗-->
          <el-dialog :title="tnm2" @close="closeqddialog2" :visible.sync="dialog2">

              <el-form class="qd-wrap" size="tiny" :inline="true" ref="xyform" :rules="rules2" :model="xyform" label-width="80px" label-position="left"  v-loading.fullscreen.lock="loading1" element-loading-text="协议信息保存中">
                  <el-form-item label="名称">
                      <el-input :disabled="true" v-model="xyform.protocol" placeholder=""></el-input>
                  </el-form-item>
                
                
                  <el-form-item label="协议选择" class="xyselect-input" prop="protocol">
                      <el-select v-model="xyform.protocol">
                          <el-option v-for="item in newxy" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
                      </el-select>
                  </el-form-item>
                  <el-form-item label="排序">
                      <el-input v-model="xyform.order" placeholder=""></el-input>
                  </el-form-item>
                  <el-form-item class="submit-btn">
                      <el-button type="primary" @click="submitxyForm('xyform')">保存</el-button>
                      <el-button @click="resetxyForm()">取消</el-button>
                  </el-form-item>

              </el-form>
          </el-dialog>
          <!--添加协议列表弹窗-->
      </div>
    </div>
  </div>  
</template>
<script>
import Nav from "../components/nav.vue";
export default {
  components: {
    Nav
  },
  data() {
    let checknumber = (rule, value, callback) => {
      if (value) {
        if (isNaN(value)) {
          callback(new Error("请输入正确的端口号"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };

    return {
      loading: false,
      loading1: false,
      xyindex: null, //删除协议数组
      dialog1: false, //驱动添加编辑弹窗
      dialog2: false, //协议2弹窗
      qdindex: 0, //当前默认0
      newxy: [], //用来判断是否已经选择过
      tnm: "新增",
      token: "", //登录参数
      srcName: "", //唯一标识名用来编辑和删除
      isedit: true, //是否可编辑
      isedit2: true, //是否可编辑2
      iseditadd: true, //是否可添加2
      drives: [], //驱动类型选择
      xyrows: [], //协议联动
      xyprotocols: [], //获取所有协议
      xyform: {
        order: null, //排序选择
        protocol: "" //协议选择
      },
      xyform2: {
        protocol: "" //协议选择
      },
      rowsqd: [],
      qdform: {
        name: "",
        prefix: "",
        host: "",
        type:'',
        port: null,
        protocols: [],
        enable: true
      },
      qdform2: {
        //用于编辑
        name: "",
        prefix: "",
        host: "",
        port: null,
        type:'',
        protocols: [],
        enable: true
      },
      rules: {
        name: [{ required: true, message: "名称不能为空。", trigger: "blur" }],
        host: [{ required: true, message: "ip地址不能为空", trigger: "blur" }],
        port: [
          { required: true, message: "端口不能为空" },
          { validator: checknumber, trigger: "blur" }
        ],
        type: [{ required: true, message: "驱动选择不能为空", trigger: "change" }]
      },
      rules2: {
        protocol: [{ required: true, message: "请选择协议", trigger: "change" }]
      }
    };
  },
  computed: {
    SystemTable: function() {
      let style = $(window).height() - 140;
      return style;
    },
    addconfighigh: function() {
      let style = { height: $(window).height() - 52 + "px" };
      return style;
    }
  },
  methods: {
    indexMethod(index) {
      return index * 2;
    },
    onchange: function(row, event, column) {
      let self = this;
      self.srcName = row.srcName;
    
      self.qdform = row;
      self.qdform2 = row;

      let xyrows = [];
      for (let i = 0; i < this.rowsqd.length; i++) {
        if (this.rowsqd[i].srcName == row.srcName) {
          this.qdindex = i;
          break;
        }
      }
      if (row.protocols.length > 0) {
        $.each(row.protocols, function(i, item) {
          let obj = {};
          obj.name = item;
          xyrows.push(obj);
        });
      }
      self.xyrows = xyrows;
      self.isedit = false;
      self.isedit2 = true;
      self.iseditadd = false; //可编辑
    },
    onchange2: function(row, event, column) {
      let self = this;
      //  self.xyform = {}; //置空

      self.xyform.protocol = row.name;
      self.xyform2.protocol = row.name;
      self.isedit2 = false;
      for (let i = 0; i < this.rows.length; i++) {
        if (this.xyrows[i].name == row.protocol) {
          self.xyindex = i;
          break;
        }
      }
    },
    editrow() {
      //编辑

      let self = this;
      self.tnm = "修改";

      self.dialog1 = true;
    },

    addqd() {
      //添加驱动
      let self = this;

      self.tnm = "新增";
      setTimeout(function(){
        self.qdform = {
            name: "",
            prefix: "",
            host: "",
            type:'',
            port: null,
            protocols: [],
            enable: true
          };
           self.$refs["qdform"].resetFields();
      },50)
     

     
     
        self.isedit = true;
        self.xyrows = [];
       self.iseditadd=true
      // self.$nextTick(function() {
       
      // });
       self.dialog1 = true;
    },
    addxy() {
      let self = this;
      self.tnm2 = "新增";
      self.xyform = {
        order: null, //排序选择
        protocol: "" //协议选择
      };
      self.ischeckselected();
      self.dialog2 = true;
      self.$nextTick(function() {
        this.$refs["xyform"].resetFields();
      });
    },
    ischeckselected() {
      //判断协议是否已经选择过
      let self = this;

      let newxy = [];
      $.each(self.xyprotocols, function(i, item) {
        let obj = {};
        if (self.xyrows.length > 0) {
          $.each(self.xyrows, function(j, k) {
            if (k.name == item) {
              obj.disabled = true;
            }
          });
        }
        obj.value = item;
        obj.label = item;
        newxy.push(obj);
      });
      self.newxy = newxy;
      //  self.xyprotocols
      // self.xyrows
    },
    editrowxy() {
      //修改协议
      let self = this;
      self.tnm2 = "修改";
      self.dialog2 = true;
      self.xyform.protocol = "";
      self.xyform.protocol = self.xyform2.protocol;
      self.ischeckselected();
    },
    deleteRow() {
      //删除行1
      let self = this;
      if (!self.isedit) {
        /*------ 确定提交按钮------*/
        this.$confirm("是否确定要删除？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            /*------ 执行操作------*/

            jQuery.ajax({
              type: "POST",
              url: "/unitalk/v1.0/device/delete.json",
              contentType: "application/json",
              data: JSON.stringify({
                Token: self.token,
                srcName: self.srcName
              }),
              dataType: "json",
              success: function(rep) {
                if (typeof rep == "string") {
                  try {
                    rep = JSON.parse(rep);
                  } catch (err) {
                    rep = {
                      Code: 99999,
                      Message: "删除失败，请稍后再试！"
                    };
                  }
                }
                if (rep.Code == 0) {
                  self.xyrows = []; //删除后归0
                  self.$message({
                    message: "数据删除成功",
                    type: "success"
                  });
                  self.lodalistdata(); //重新加载一次数据
                  self.srcName = "";

                  self.isedit = true;
                  self.iseditadd = true; //可编辑
                } else {
                  self.$message.error(rep.Message);
                }
              }
            });
            /*------ 执行操作------*/
          })
          .catch(() => {
            return false;
          });
        /*------ 确定提交按钮------*/
      } else {
        self.$message({
          message: "请选择需要删除的行",
          type: "warning"
        });
      }
    },
    deleteRowxy() {
      //删除协议部分
      let self = this;
      if (!self.isedit2) {
        /*------ 确定提交按钮------*/
        this.$confirm("是否确定要删除？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            /*------ 执行操作------*/
            self.rowsqd.splice(0, 1);
            self.xyrows = [];
            self.qdform2.Token = self.token;
            self.qdform2.protocols.splice(self.xyindex, 1);
            self.loading1 = true;
            jQuery.ajax({
              type: "POST",
              url: "/unitalk/v1.0/device/update.json",
              contentType: "application/json",
              data: JSON.stringify(self.qdform2),
              dataType: "json",
              success: function(rep) {
                if (typeof rep == "string") {
                  try {
                    rep = JSON.parse(rep);
                  } catch (err) {
                    rep = {
                      Code: 99999,
                      Message: "数据初始化失败，请稍后再试！"
                    };
                  }
                }

                if (rep.Code == 0) {
                  self.$message({
                    message: "协议删除成功",
                    type: "success"
                  });

                  self.lodalistdata(); //重新加载一次数据
                  self.$nextTick(function() {
                    setTimeout(function() {
                      self.loading1 = false;
                      $("#qdlist")
                        .find(".el-table__row")
                        .eq(self.qdindex)
                        .click();
                    }, 500);
                  });
                } else {
                  self.$message.error(rep.Message);
                }
              }
            });
            /*------ 执行操作------*/
          })
          .catch(() => {
            return false;
          });
        /*------ 确定提交按钮------*/
      } else {
        self.$message({
          message: "请选择需要删除的行",
          type: "warning"
        });
      }
    },
    closeqddialog() {
      //关闭弹窗
      let self = this;

      self.dialog1 = false;

      // self.isedit=true
      // self.iseditadd=true
      //  self.qdform = {
      //     name: "",
      //     prefix: "",
      //     host: "",
      //     port: null,
      //     protocols: [],
      //     enable: true
      //   };
      // self.$refs["qdform"].resetFields();

      // this.$refs['qdform'].resetFields();
    },
    closeqddialog2() {
      //关闭弹窗
      let self = this;
      self.dialog2 = false;
      self.xyform = {
        order: null, //排序选择
        protocol: "" //协议选择
      };
      this.$refs["xyform"].resetFields();
    },
    resetxyForm() {
      let self = this;
      self.closeqddialog2();
    },
    resetqdForm() {
      //重置按钮

      let self = this;
      // if (self.tnm == "新增") {
      //   self.qdform = {
      //     name: "",
      //     prefix: "",
      //     host: "",
      //     port: null,
      //     protocols: [],
      //     enable: true
      //   };
      // } else {
      //   self.qdform = self.qdform2;
      // }
      self.closeqddialog();
      // self.$refs["qdform"].resetFields();
    },
    resetform() {
      left = this;
      self.qdform = {
        name: "",
        prefix: "",
        host: "",
        port: null,
        protocols: [],
        enable: true
      };
    },
    submitqdForm(form) {
      let self = this;

      self.$refs[form].validate(valid => {
        if (valid) {
          let linku;
          /*------ 执行操作------*/
          if (self.tnm == "新增") {
            let ishave = false;
            if (self.rowsqd.length > 0) {
              $.each(self.rowsqd, function(i, item) {
                if (item.srcName == self.qdform.name) {
                  ishave = true;
                  return false;
                }
              });
            }
            if (ishave) {
              self.$message({
                message: "该驱动已存在",
                type: "error"
              });
              return false;
            }
            linku = "/unitalk/v1.0/device/add.json";
          } else {
            linku = "/unitalk/v1.0/device/update.json";
          }
          self.qdform.Token = self.token;
          self.loading = true;
          jQuery.ajax({
            type: "POST",
            url: linku,
            contentType: "application/json",
            data: JSON.stringify(self.qdform),
            dataType: "json",
            success: function(rep) {
              if (typeof rep == "string") {
                try {
                  rep = JSON.parse(rep);
                } catch (err) {
                  rep = {
                    Code: 99999,
                    Message: "数据初始化失败，请稍后再试！"
                  };
                }
              }
              if (rep.Code == 0) {
                self.loading = false;
                if (self.tnm == "新增") {
                  self.$message({
                    message: "数据保存成功",
                    type: "success"
                  });
                  // self.closeqddialog(); //成功后关闭弹窗
                  // self.lodalistdata(); //重新加载一次数据

                  // self.resetform();
                   self.qdform = {
                      name: "",
                      prefix: "",
                      host: "",
                      type:'',
                      port: null,
                      protocols: [],
                      enable: true
                    };
                } else {
                  self.$message({
                    message: "驱动修改成功",
                    type: "success"
                  });
                }
                self.closeqddialog(); //成功后关闭弹窗
                self.lodalistdata(); //重新加载一次数据
                self.xyrows = [];
                // self.$nextTick(function() {

                //   setTimeout(function() {
                //     $("#qdlist")
                //       .find(".el-table__row")
                //       .eq(self.qdindex)
                //       .click();

                //   }, 1000);
                // });
                self.resetform();

                self.$refs["qdform"].resetFields();
              } else {
                self.$message.error(rep.Message);
              }
            }
          });
          /*------ 执行操作------*/
        } else {
          return false;
        }
      });
    },
    submitxyForm(form) {
      let self = this;

      self.$refs[form].validate(valid => {
        if (valid) {
          /*------ 执行操作------*/

          self.qdform2.Token = self.token;

          if (self.tnm2 == "新增") {
            self.qdform2.protocols.push(self.xyform.protocol);
            //self.xyrows.push(self.xyform.protocol);
          } else {
            self.qdform2.protocols.splice(self.xyindex, 1);

            self.qdform2.protocols.push(self.xyform.protocol);
            //  self.xyrows.splice(self.xyindex,1);
            //  self.xyrows.push(self.xyform.protocol);
          }
          self.loading1 = true;
          jQuery.ajax({
            type: "POST",
            url: "/unitalk/v1.0/device/update.json",
            contentType: "application/json",
            data: JSON.stringify(self.qdform2),
            dataType: "json",
            success: function(rep) {
              if (typeof rep == "string") {
                try {
                  rep = JSON.parse(rep);
                } catch (err) {
                  rep = {
                    Code: 99999,
                    Message: "数据初始化失败，请稍后再试！"
                  };
                }
              }

              if (rep.Code == 0) {
                if (self.tnm2 == "新增") {
                  self.$message({
                    message: "协议添加成功",
                    type: "success"
                  });
                } else {
                  self.$message({
                    message: "协议修改成功",
                    type: "success"
                  });
                }
                self.closeqddialog2(); //成功后关闭弹窗
                // self.lodalistdata2()
                //self.lodalistdata(); //重新加载一次数据
                self.$nextTick(function() {
                  self.loading1 = false;
                  setTimeout(function() {
                    $("#qdlist")
                      .find(".el-table__row")
                      .eq(self.qdindex)
                      .click();
                  }, 500);
                });
              } else {
                self.$message.error(rep.Message);
              }
            }
          });
          /*------ 执行操作------*/
        } else {
          return false;
        }
      });
    },
    formattertxt(row, column, cellValue) {
      if (row.enable) {
        return "是";
      } else {
        return "否";
      }
    },
    lodalistdata() {
      let self = this;
      jQuery.ajax({
        type: "POST",
        url: "/unitalk/v1.0/devices.json",
        contentType: "application/json",
        data: JSON.stringify({
          Token: self.token
        }),
        dataType: "json",
        success: function(rep) {
          if (typeof rep == "string") {
            try {
              rep = JSON.parse(rep);
            } catch (err) {
              rep = {
                Code: 99999,
                Message: "取数据失败，请稍后再试！"
              };
            }
          }
          if (rep.Code == 0) {
            self.rowsqd = rep.Response;
          } else {
            self.$message.error(rep.Message);
          }
        }
      });
    },

    getlistdrives() {
      //获取所有驱动类型
      let self = this;
      jQuery.ajax({
        type: "POST",
        url: "/unitalk/v1.0/drives.json",
        contentType: "application/json",
        data: JSON.stringify({
          Token: self.token
        }),
        dataType: "json",
        success: function(rep) {
          if (typeof rep == "string") {
            try {
              rep = JSON.parse(rep);
            } catch (err) {
              rep = {
                Code: 99999,
                Message: "获取数据失败，请稍后再试"
              };
            }
          }
          if (rep.Code == 0) {
            self.drives = rep.Response;
            let newdrives = [];
            $.each(rep.Response, function(i, item) {
              let obj = {};
              obj.value = item;
              obj.label = item;
              newdrives.push(obj);
            });
             self.drives= newdrives;
          } else {
            self.$message.error(rep.Message);
          }
        }
      });
    },
    getlistprotocols() {
      //获取所有协议列表
      let self = this;
      jQuery.ajax({
        type: "POST",
        url: "/unitalk/v1.0/protocols.json",
        contentType: "application/json",
        data: JSON.stringify({
          Token: self.token
        }),
        dataType: "json",
        success: function(rep) {
          if (typeof rep == "string") {
            try {
              rep = JSON.parse(rep);
            } catch (err) {
              rep = {
                Code: 99999,
                Message: "获取数据失败，请稍后再试"
              };
            }
          }
          if (rep.Code == 0) {
            self.xyprotocols = rep.Response;
          } else {
            self.$message.error(rep.Message);
          }
        }
      });
    },
    gettoken(v) {
      //获取登录参数
      let self = this;
      self.token = v;
      /*------执行用户基本信息------*/
      self.lodalistdata(); //获取网管列表数据
      self.getlistdrives(); //获取所有驱动类型
      self.getlistprotocols(); //获取所有协议列表
    }
  },
  mounted: function() {
    let self = this;
    self.gettoken(); //登录后执行操作
  },
  watch: {}
};
</script>


